const Captcha = require('../utils/useCaptcha');
const DB = require('../modules/db');

const captcha = new Captcha();

const captchaCode = async ctx => {
  try {
    const {data} = captcha.initCaptcha();
    ctx.body = {
      code: 200,
      msg: '获取验证码成功',
      success: true,
      data
    };
  } catch (error) {
    ctx.throw(error);
  }
};

// 注册
const register = async ctx => {
  try {
    const { username, password, captchaCode } = ctx.request.body;
    if (captchaCode.toLocaleLowerCase() === captcha.bufferToken.toLocaleLowerCase()) {
      const sql = `INSERT INTO user(username, password) VALUES ('${username}', '${password}');`;
      await DB.query(sql);
      ctx.body = {
        code: 200,
        msg: '注册成功',
        success: true
      };
    }
    else {
      ctx.body = {
        code: 200,
        msg: '注册失败，验证码错误',
        success: false
      };
    }
    
  } catch (error) {
    ctx.throw(error);
  }
};

// 登录
const login = async ctx => {
  try {
    const { username, password, captchaCode } = ctx.request.body;
    // 验证码是否正确
    if (captchaCode.toLocaleLowerCase() === captcha.bufferToken.toLocaleLowerCase()) {
      const sql = `select * from user`;
      const userList = await DB.query(sql);
      // 查找账户
      const user = userList.find(item => item.username === username);
      // 用户不存在
      if (!user) {
        ctx.body = {
          code: 200,
          msg: '该账号不存在，请注册后再登录',
          success: false
        };
        return;
      }
      // 密码错误
      if (user.password !== password) {
        ctx.body = {
          code: 200,
          msg: '密码错误',
          success: false
        };
        return;
      }

      ctx.body = {
        code: 200,
        msg: '登录成功',
        success: true
      };
      return;

    }

    ctx.body = {
      code: 200,
      msg: '验证码错误',
      success: false
    };

  } catch (error) {
    ctx.throw(error);
  }
};



module.exports = {
  captchaCode,
  register,
  login
};